/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.annotation.WebServlet;
import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.*;
import stateless.FoodMateEJBRemote;
import java.lang.*;


/**
 *
 * @author stan
 */
@WebServlet(name="FoodMateServlet", urlPatterns={"/FoodMateServlet","/RestaurantAdd","/restInfo","/reserveRest","/PersonalInfo", "/reserveAjax", "/AdminPage", "/acceptRsv", "/BanPage", "/UnbanPage","/requestToBeFM"})
public class FoodMateServlet extends HttpServlet {

    @EJB
    private FoodMateEJBRemote foodmateEJB;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        HttpSession session = request.getSession();
        PrintWriter out = response.getWriter();
        String urlPath = request.getServletPath();
        String Style = request.getParameter("Style");
        String Location = request.getParameter("Location");
        String RestaurantName = request.getParameter("RestaurantName");
        String FBid = request.getParameter("username");
        String FBid3 = request.getParameter("username3");
        String BanOrUnbanId = request.getParameter("username4");
        
        if (urlPath.equals("/reserveAjax")) {
            //String dt = request.getParameter("selectTime");
            out.println(
                "{" +
                " id:'ss'" +
                "}"
                );

            out.println("dd");
            out.flush();
            out.close();
        }

        if (urlPath.equals("/requestToBeFM")) {
            String RequestUser = request.getParameter("requestUsrId");
            String dt = (String) session.getAttribute( "reserveDate");
            java.util.Date myDate = new java.util.Date(dt);
            java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
            
            FoodMateEJBRemote.ReserveInfo reserve = new FoodMateEJBRemote.ReserveInfo();
            reserve.Host = Integer.parseInt(RequestUser);
            reserve.Date = sqlDate;
            reserve.Time = (Integer)session.getAttribute( "reserveTime");
            reserve.Memo = "I am going to there!";
            reserve.RestaurantId = (Integer)session.getAttribute( "reserveRid");
            reserve.Status = 0;
            reserve.UserId =(Integer)session.getAttribute("FBid");
            if (foodmateEJB.AddReserveInfo(reserve)==false) {
                    out.print("You have not request successfully!");
            }
                else {
                    out.print("You have request successfully!");
                    String url = "reservePage.jsp";
                    request.getRequestDispatcher(url).forward(request, response);
            }
            //String url = "restaurantInfo.jsp";
            //request.getRequestDispatcher(url).forward(request, response);
        }

        if (urlPath.equals("/AdminPage")) {
            if( FBid3.equals("839098116") || FBid3.equals("1118094785") || FBid3.equals("1140416666"))
            {
                ArrayList<FoodMateEJBRemote.User> user = foodmateEJB.ListAllUser();
                for(int i = 0; i < user.size(); i++)
                {
                    if( user.get(i).Id == 839098116 || user.get(i).Id == 1118094785 || user.get(i).Id == 1140416666 )
                        continue;

                    out.print("<div id='"+user.get(i).Id +"'>" + user.get(i).Id);

                    if(user.get(i).Baned == false)
                    {
                        out.println(" <img class='restPhoto' src="+user.get(i).Picture+" style='height:50px'> ");
                        out.println("<form method=\"GET\" action=\"BanPage\">");
                        out.print("<INPUT id=" + user.get(i).Id + "\" TYPE=hidden NAME=username4 SIZE=20 value=\"" + user.get(i).Id + "\">");
                        out.print("<INPUT id=" + FBid3+ "\" TYPE=hidden NAME=username3 SIZE=20 value=\"" + FBid3 + "\">");
                        out.print(" <input id=\"btn1\" type=\"submit\" value=\"Ban\" name=\"btnAdminPage1\">");
                        out.println("</form>");
                    }
                    else
                    {
                        out.println(" <img class='restPhoto' src="+user.get(i).Picture+" style='height:50px'> ");
                        out.println("<form method=\"GET\" action=\"UnbanPage\">");
                        out.print("<INPUT id=" + user.get(i).Id + "\" TYPE=hidden NAME=username4 SIZE=20 value=\"" + user.get(i).Id + "\">");
                        out.print("<INPUT id=" + FBid3+ "\" TYPE=hidden NAME=username3 SIZE=20 value=\"" + FBid3 + "\">");
                        out.print(" <input id=\"btn2\" type=\"submit\" value=\"Unban\" name=\"btnAdminPage2\">");
                        out.println("</form>");

                    }
                    out.print("</div>");
                }
            }
            else
            {
                out.println("You are not Admin!!!");
                String url = "index.jsp";
                request.getRequestDispatcher(url).forward(request, response);
            }
            
        //    out.println(Integer.parseInt(FBid3));
        //    FoodMateEJBRemote.User user = new FoodMateEJBRemote.User();
        //        user.Id = Integer.parseInt(FBid);
        //        user.Baned = false;
        //        user.Picture = "https://graph.facebook.com/"+FBid+"/picture";

        }
        if (urlPath.equals("/BanPage")) {
            boolean bool = foodmateEJB.BanUser(Integer.parseInt(BanOrUnbanId));

            if(bool){
                String url = "/AdminPage";
                request.getRequestDispatcher(url).forward(request, response);
            }
        }

        if (urlPath.equals("/UnbanPage")) {
            boolean bool = foodmateEJB.UnbanUser(Integer.parseInt(BanOrUnbanId));

            if(bool)
            {
                String url = "/AdminPage";
                request.getRequestDispatcher(url).forward(request, response);
            }
        }



        if (urlPath.equals("/RestaurantAdd")) {
            FoodMateEJBRemote.Restaurant rest = new FoodMateEJBRemote.Restaurant();
            rest.Name = request.getParameter("RestaurantName");
            rest.Style = request.getParameter("RestaurantStyle");
            rest.Location = request.getParameter("RestaurantLocation");
            rest.Email = request.getParameter("RestaurantEmail");
            rest.Picture = request.getParameter("RestaurantPhoto");
            rest.Description = request.getParameter("RestaurantDescription");
            foodmateEJB.AddRestaurant(rest);
            String url = "addRest.jsp";
            request.getRequestDispatcher(url).forward(request, response);
            //response.getWriter().println("OIOIOIOIO");
            //foodmateEJB.test();
        }
        if (urlPath.equals("/restInfo")) {
            if (request.getParameter("restId")!="") {
            FoodMateEJBRemote.Restaurant rest;// = new FoodMateEJBRemote.Restaurant();
            //out.println(request.getParameter("restId"));
            rest=foodmateEJB.FindRestaurant(Integer.parseInt(request.getParameter("restId")));
      /*      out.println("<script type='text/javascript' src='js/jquery.js'></script>");
            out.println("<script type='text/javascript' src='js/jquery.livequery.js'></script>");
            out.println("<script type='text/javascript' src='js/foodMate.js'></script>");
            out.println("<script type='text/javascript' src='js/jquery.ui.core.js'></script>");
            out.println("<script type='text/javascript' src='js/jquery.ui.datepicker.js'></script>");
            out.println("<script type='text/javascript' src='js/calendarDateInput.js'></script>");*/
            session.setAttribute( "restId", rest.Id );
            session.setAttribute( "restLoc", rest.Location );
            session.setAttribute( "restEmail", rest.Email );
            session.setAttribute( "restPic", rest.Picture );
            session.setAttribute( "restDesc", rest.Description );
            session.setAttribute( "restName", rest.Name );
            String url = "reservePage.jsp?time="+request.getParameter("Time");
            request.getRequestDispatcher(url).forward(request, response);
            /*
            out.println("<div> <font size='10'>Restaurant:"+rest.Name+"</font></div>");
            out.println("<div> Location:"+rest.Location+"</div>");
            out.println("<div> website: "+rest.Email+"</div>");
            out.println("<img id='restaurantPic' src='"+rest.Picture+"'>");
            out.println("<div>"+rest.Description+"</div>");
            out.println("<div>"+session.getAttribute("FBid")+"</div>");
            
            out.println("<form method='GET' action='reserveRest'>");
            out.println("<div> Time");
            out.println("<SELECT NAME='Time'>");
            out.println("<OPTION VALUE='1'>Breakfast");
            out.println("<OPTION VALUE='2'>Lunch");
            out.println("<OPTION VALUE='3'>Dinner");
            out.println("</SELECT>");
            out.println("</div>");
            out.println("<p><input id='restInfo' type='submit' value='select' name='C1' ></p>");
            out.println("</form>");
            out.println("<form>");
            out.println("<p>Date: <script>DateInput('orderdate', true, 'DD-MON-YYYY')</script></p>");
            out.println("<input type='button' onClick='alert(this.form.orderdate.value)' value='Show date value passed'>");
            out.println("</form>");


            ArrayList<FoodMateEJBRemote.ReserveInfo> rsvInfo = foodmateEJB.FindReserveInfoByRestaurant(rest.Id);
            for(int i = 0; i < rsvInfo.size(); i++)
            {
                out.println("<div id='"+rsvInfo.get(i).Id +"'><img class='restPhoto' src='https://graph.facebook.com/"+rsvInfo.get(i).UserId +"/picture' style='height:50px'><INPUT id='restId' TYPE=hidden VALUE='"+rsvInfo.get(i).UserId+"' NAME=restId SIZE=20></div>");
                //out.println(rst.get(i).Name);
            }
            */
           // int oId = Integer.parseInt(orderId.trim());
            }
            else {
                String url = "index.jsp";
                request.getRequestDispatcher(url).forward(request, response);
            }
            
        }
        if (urlPath.equals("/reserveRest")) {
            FoodMateEJBRemote.ReserveInfo reserve = new FoodMateEJBRemote.ReserveInfo();
            java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
            reserve.Host = (Integer)session.getAttribute("FBid");
            reserve.Date = sqlDate;
            reserve.Time = Integer.parseInt(request.getParameter("Time"));
            reserve.Memo = "I am going to there!";
            reserve.RestaurantId = (Integer)session.getAttribute("restId");
            reserve.Status = 1;
            reserve.UserId =(Integer)session.getAttribute("FBid");
            //out.println("sss");
            //out.println(session.getAttribute("theName"));
            foodmateEJB.AddReserveInfo(reserve);
            /*
            FoodMateEJBRemote.Restaurant rest = new FoodMateEJBRemote.Restaurant();
            ArrayList<FoodMateEJBRemote.ReserveInfo> rsv = foodmateEJB.FindReserveInfoByRestaurant(Integer.parseInt((String)session.getAttribute( "restId")));
            for(int i = 0; i < rsv.size(); i++)
            {
                out.print("<div id='"+rsv.get(i).UserId +"'><img class='restPhoto' src='https://graph.facebook.com/"+rsv.get(i).UserId +"/picture' style='height:50px'/><INPUT id='restId' TYPE=hidden VALUE='"+rsv.get(i).UserId+"' NAME=restId SIZE=20></div>");
                FoodMateEJBRemote.User usr = new FoodMateEJBRemote.User();
                usr = foodmateEJB.FindUser(rsv.get(i).UserId);
                out.println(usr.Name);
            }
            //rest = foodmateEJB.FindRestaurant(Integer.parseInt((String)session.setAttribute( "restId")));
            //foodmateEJB.FindReserveInfoByRestaurant(session.setAttribute( "restId"));*/
            session.setAttribute( "reserveTime", request.getParameter("Time") );
            int time = Integer.parseInt(request.getParameter("Time"));
            String url = "restaurantInfo.jsp?time="+request.getParameter("Time");
            request.getRequestDispatcher(url).forward(request, response);
        }

        response.setContentType("text/html;charset=UTF-8");
        
        try {
            /* TODO output your page here*/
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet TestServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<script type='text/javascript' src='js/jquery.js'></script>");
            out.println("<script type='text/javascript' src='js/jquery.livequery.js'></script>");
            out.println("<script type='text/javascript' src='js/foodMate.js'></script>");
            out.println("<link href='css/foodMate.css' rel='stylesheet' type='text/css' />");
            out.println("<div id='container'>");
            out.println("<div id='main'>");
            
            /*
            out.println("Style is : " + "  " + Style + "  " + "<br>" );
            out.println("Location is : " + "  " + Location + "  " + "<br>" );
            out.println("Name is : " + "  " + RestaurantName + "  " + "<br>" );
            out.println("FBid is : " + "  " + FBid + "  " + "<br>" );*/
            //out.println(foodmateEJB.Hello());
           // out.println(foodmateEJB.test());

            FoodMateEJBRemote.Restaurant tmp = new FoodMateEJBRemote.Restaurant();
            //tmp.Name = "yo";
            //tmp.Style = "Chinese";
            //tmp.Location = "Manhattan";

            //foodmateEJB.AddRestaurant(tmp);
            out.println();
            if (urlPath.equals("/FoodMateServlet")) {
                String realname = request.getParameter("realname");
         
                session.setAttribute("FBid", Integer.parseInt(FBid));
                FoodMateEJBRemote.User user = new FoodMateEJBRemote.User();
                user.Id = Integer.parseInt(FBid);
                user.Baned = false;
                user.Description="nothing";
                user.Email = "xli@yahoo.com";
                user.Gender = true;
                user.Picture = "https://graph.facebook.com/"+FBid+"/picture";
                user.Password = "haha";
                user.Name = ""; // didnt get user name from FBid yet(doesnt need too)
                // Insert UserInfo here
                foodmateEJB.AddUser(user);
                out.print("<a href='index.jsp'>HOME</a>");
                ArrayList<FoodMateEJBRemote.Restaurant> rst = foodmateEJB.FindRestaurant(Style, Location, RestaurantName);
                for(int i = 0; i < rst.size(); i++)
                {
                    out.print("<div id='"+rst.get(i).Id +"'><img class='restPhoto' src="+rst.get(i).Picture+" style='height:50px'><INPUT id='restId' TYPE=hidden VALUE='"+rst.get(i).Id+"' NAME=restId SIZE=20></div>");
                    out.println(rst.get(i).Name);
                }

                out.println("<div id='SelectRest'>");
                out.println("<form method='GET' action='restInfo'>");
                out.println("<INPUT id='selectRestId' TYPE=hidden NAME=restId SIZE=20>");
                out.println("<p><input id='restInfo' type='submit' value='select' name='C1' ></p>");
                out.println("</form>");
                out.println("</div>");
            }

            if (urlPath.equals("/PersonalInfo")) {
                int id = -1;
                String FBid2 = request.getParameter("username2");

                out.println("<a href='index.jsp'>back</a>");

                if(!FBid2.equals(""))
                {
                    id = Integer.parseInt(FBid2);
                    session.setAttribute("FBid", id);
                }
                else
                {
                    String url = "index.jsp";
                    request.getRequestDispatcher(url).forward(request, response);
                }


                FoodMateEJBRemote.User user = foodmateEJB.FindUser(id);
                if(user == null)
                {
                    user.Id = id;
                    user.Baned = false;
                    user.Description="nothing";
                    user.Email = "xli@yahoo.com";
                    user.Gender = true;
                    user.Picture = "https://graph.facebook.com/"+id+"/picture";
                    user.Password = "haha";
                    user.Name = ""; // didnt get user name from FBid yet(doesnt need too)
                    // Insert UserInfo here
                    foodmateEJB.AddUser(user);
                }
                out.print("<div id='"+ user.Id +"'><img class='restPhoto' src="+ user.Picture +" style='height:50px'></div>");


                ArrayList<FoodMateEJBRemote.ReserveInfo> rsv = foodmateEJB.FindReserveInfoByUser(id);
                ArrayList<FoodMateEJBRemote.ReserveInfo> rsvhost = foodmateEJB.FindReserveInfoByHost(id);
                out.println("<font color='red'>you host</font><br>");
                int num = 1;
                for(int i = 0; i < rsv.size(); i++)
                {
                    if(rsv.get(i).Host == id)
                    {
                        out.println(num);
                        num++;
                        FoodMateEJBRemote.Restaurant rst = foodmateEJB.FindRestaurant(rsv.get(i).RestaurantId);
                        out.print("<div id='"+rsv.get(i).RestaurantId +"'><img class='restPhoto' src="+rst.Picture+" style='height:50px'><INPUT id='restId' TYPE=hidden VALUE='"+rst.Id+"' NAME=restId SIZE=20></div>");
                        out.println(rst.Name+"<br>");
                        out.println(rsv.get(i).Date.toString()+"<br>");
                        if(rsv.get(i).Time == 1)
                            out.println("breakfast"+"<br>");
                        else if(rsv.get(i).Time == 2)
                            out.println("lunch"+"<br>");
                        else if(rsv.get(i).Time == 3)
                            out.println("dinner"+"<br>");
                        out.println(rsv.get(i).Memo+"<br>");
                        out.println("who else are going to:<br>");
                        for(int j = 0; j < rsvhost.size(); j++)
                        {
                            if(rsv.get(i).RestaurantId == rsvhost.get(j).RestaurantId && rsv.get(i).Date.equals(rsvhost.get(j).Date) && rsv.get(i).Time == rsvhost.get(j).Time && rsv.get(i).UserId != rsvhost.get(j).UserId)
                            {
                                FoodMateEJBRemote.User usr = foodmateEJB.FindUser(rsvhost.get(j).UserId);
                                out.print("<div id='"+ usr.Id +"'><img class='restPhoto' src="+ usr.Picture +" style='height:50px'><INPUT id='rsvId' TYPE=hidden VALUE='"+rsvhost.get(j).Id+"' NAME=usrId SIZE=20></div>");
                                out.println(rsvhost.get(j).Memo+"<br>");
                                if(rsvhost.get(j).Status == 0)
                                {
                                    out.println("<div id='Accept'>");
                                    out.println("<form method='GET' action='acceptRsv'>");
                                    out.println("<INPUT id='selectRsvId' TYPE='hidden' NAME='rsvId' value='"+rsvhost.get(j).Id+"' SIZE=20>");
                                    out.println("<INPUT id='FBid2' TYPE='hidden' NAME='username2' value='"+FBid2+"' SIZE=20>");
                                    out.println("<p><input id='accpetRsv' type='submit' value='accept' name='C1' ></p>");
                                    out.println("</form>");
                                    out.println("</div>");
                                }
                            }
                        }
                    }
                }
                out.println("<font color='red'>you are going to attend</font><br>");
                num = 1;
                for(int i = 0; i < rsv.size(); i++)
                {
                    if(rsv.get(i).Host != id)
                    {
                        out.println(num);
                        num++;
                        FoodMateEJBRemote.Restaurant rst = foodmateEJB.FindRestaurant(rsv.get(i).RestaurantId);
                        out.print("<div id='"+rsv.get(i).RestaurantId +"'><img class='restPhoto' src="+rst.Picture+" style='height:50px'><INPUT id='restId' TYPE=hidden VALUE='"+rst.Id+"' NAME=restId SIZE=20></div>");
                        out.println(rst.Name+"<br>");
                        out.println(rsv.get(i).Date.toString()+"<br>");
                        if(rsv.get(i).Time == 1)
                            out.println("breakfast"+"<br>");
                        else if(rsv.get(i).Time == 2)
                            out.println("lunch"+"<br>");
                        else if(rsv.get(i).Time == 3)
                            out.println("dinner"+"<br>");
                        out.println(rsv.get(i).Memo+"<br>");
                        out.println("host:"+"<br>");
                        out.println(rsv.get(i).Host+"<br>");
                        FoodMateEJBRemote.User usr = foodmateEJB.FindUser(rsv.get(i).Host);
                        out.print("<div id='"+ usr.Id +"'><img class='restPhoto' src="+ usr.Picture +" style='height:50px'><INPUT id='usrId' TYPE=hidden VALUE='"+usr.Id+"' NAME=usrId SIZE=20></div>");
                        if(rsv.get(i).Status == 0)
                            out.println("the host has not accepted yet<br>");
                    }
                }
            }

            if (urlPath.equals("/acceptRsv"))
            {
                FoodMateEJBRemote.ReserveInfo rsv = foodmateEJB.FindReserveInfo(Integer.parseInt(request.getParameter("rsvId")));
                rsv.Status = 1;
                foodmateEJB.UpdateReserveInfo(rsv);
                String url = "PersonalInfo";
                request.getRequestDispatcher(url).forward(request, response);
            }
            /*tmp = rst.get(rst.size()-1);
            tmp.Name = "ha";
            tmp.Email = "p";
            tmp.Picture = "p";
            tmp.Description = "p";


            out.println(tmp.Id);

            out.println(foodmateEJB.UpdateRestaurant(tmp));
            rst = foodmateEJB.FindRestaurant("Chinese", "Manhattan");
            for(int i = 0; i < rst.size(); i++)
            {
                out.println(rst.get(i).Name);
            }

            tmp = rst.get(rst.size()-1);
            out.println(tmp.Id);
            out.println(foodmateEJB.DeleteRestaurant(tmp));

            rst = foodmateEJB.FindRestaurant("Chinese", "Manhattan");
            for(int i = 0; i < rst.size(); i++)
            {
                out.println(rst.get(i).Name);
            }*/
            out.println("</div>");
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
